package hu.bme.gabor.onlab.webapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class WebapptestServlet extends HttpServlet {
	                                              
	public static final String REGISTRATION_ID = "APA91bH9mk1AhKqeq8JG2vD7iQ8DV8Mo-BFOUAUnGgvUeO3bIPcHqY2qMD7BOezgNRDqNjlrZoKBRnfF0leUw8Zw3OiK9pPuE7SfTIMTL-nkaUbd8iENDnCmPl1nUhN4h4KaUXdxLGaLih8lIqMQySu5oo-OsRSdcQ";
	public static final String email = "tgabor.flyr@gmail.com";
	public static final String password = "348gabiK90";
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		//Enumeration<?> e = req.getParameterNames();
		PrintWriter out = resp.getWriter ();
		String message = req.getParameter("message");
		
		out.println(message);
		
		/*while (e.hasMoreElements()) {
			String name = (String)e.nextElement();
			String value = req.getParameter(name);
			out.println(name + " = " + value);
		}*/
		
		//resp.setContentType("text/html");

		String token = getToken(email, password);
		//String message = req.getParameter("message");

		if (message != null) {
			int respi = sendMessage(token, REGISTRATION_ID, message);
			out.println("http response: "+respi);
		}
		
		out.close();
		
		
		
	}
	
	
	public static String getToken(String email, String password) throws IOException {

		StringBuilder builder = new StringBuilder();
		builder.append("Email=").append(email).append("&Passwd=").append(password);
		builder.append("&accountType=GOOGLE").append("&source=MyLittleExample").append("&service=ac2dm");

		
		byte[] data = builder.toString().getBytes();
		URL url = new URL("https://www.google.com/accounts/ClientLogin");
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setUseCaches(false);
		con.setDoOutput(true);
		con.setRequestMethod("POST");
		con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		con.setRequestProperty("Content-Length", Integer.toString(data.length));

		OutputStream output = con.getOutputStream();
		output.write(data);
		output.close();

		BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String line = null;
		String auth_key = null;
		while ((line = reader.readLine()) != null) {
			if (line.startsWith("Auth=")) {
				auth_key = line.substring(5);
			}
		}

		return auth_key;
	}
	

	public static int sendMessage(String auth_token, String registrationId, String message) throws IOException {

		StringBuilder postDataBuilder = new StringBuilder();
		postDataBuilder.append("registration_id").append("=").append(registrationId);
		postDataBuilder.append("&").append("collapse_key").append("=").append("0");
		postDataBuilder.append("&").append("data.payload").append("=").append(URLEncoder.encode(message, "UTF-8"));

		byte[] postData = postDataBuilder.toString().getBytes("UTF-8");

		URL url = new URL("https://android.clients.google.com/c2dm/send");

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type",	"application/x-www-form-urlencoded;charset=UTF-8");
		conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
		conn.setRequestProperty("Authorization", "GoogleLogin auth="+ auth_token);
		
		OutputStream out = conn.getOutputStream();
		out.write(postData);
		out.close();

		return conn.getResponseCode();
	}
	
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

/*		PrintWriter out = response.getWriter();
		response.setContentType("text/html");

		String token = getToken(email, password);
		String message = request.getParameter("message");

		if (message != null) {
			int resp = sendMessage(token, REGISTRATION_ID, message);
			out.println("http response: "+resp);
		}
		
		out.close();*/
	}
			
}
